package com.mangix.test;

import org.json.simple.JSONValue;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by Ahan on 2014/5/12.
 */
public class Client {
    public static void main(String[] args) throws Exception {
        Selector selector = Selector.open();
        SocketChannel initClientSocketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9091));
        // You must set the Channel to non-blocking.
        initClientSocketChannel.configureBlocking(false);
        initClientSocketChannel.register(selector, SelectionKey.OP_WRITE);

        while (selector.select() > 0) {
            Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
                SelectionKey key = selectedKeys.next();
                selectedKeys.remove();
                if (!key.isValid()) {
                    continue;
                }
                if (key.isReadable()) {
                    SocketChannel clientSocketChannel = (SocketChannel) key.channel();
                    ByteBuffer inBuf = ByteBuffer.allocate(1024);
                    clientSocketChannel.read(inBuf);
                    inBuf.flip();
                    Charset charset = Charset.forName("utf-8");
                    CharsetDecoder decoder = charset.newDecoder();
                    CharBuffer charBuffer = decoder.decode(inBuf);
                    System.out.println(charBuffer);
                    clientSocketChannel.close();
                    System.exit(0);
                } else if (key.isWritable()) {
                    while (true) {
                        SocketChannel clientSocketChannel = (SocketChannel) key.channel();
//                    ByteBuffer outBuf = ByteBuffer.allocate(1024);
//                    outBuf.put(("Current Time is " + new Date()).getBytes());
//                    outBuf.flip();
                        System.out.println("!");

                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        Map jsonMap = new LinkedHashMap();
                        jsonMap.put("method", "closest_preceding_finger");
                        jsonMap.put("id", "3");
                        buffer.put(JSONValue.toJSONString(jsonMap).getBytes());
                        buffer.flip();
                        try {
                            clientSocketChannel.write(buffer);
                            clientSocketChannel.register(selector, SelectionKey.OP_READ);
                        } catch (IOException e) {
                            System.out.println("!!");
                            key.cancel();
                            try {
                                clientSocketChannel.close();
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                            e.printStackTrace();
                            return;
                        }

//                    clientSocketChannel.write(outBuf);
                        Thread.sleep(2000);
//                    clientSocketChannel.register(selector, SelectionKey.OP_WRITE);
//                    clientSocketChannel.close();
                    }
                }
            }
        }
    }
}
